package cd.cdyb.sms.service.impl;

import cd.cdyb.sms.dao.WhiteListDao;
import cd.cdyb.sms.domain.WhiteList;
import cd.cdyb.sms.dto.PageResult;
import cd.cdyb.sms.dto.WhiteListDto;
import cd.cdyb.sms.dto.query.WhiteListQueryDto;
import cd.cdyb.sms.service.RedisService;
import cd.cdyb.sms.service.WhiteListService;
import cd.cdyb.sms.utils.CacheUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service("whiteListService")
public class WhiteListServiceImpl implements WhiteListService {

    @Resource
    private WhiteListDao whiteListDao;

    @Resource
    private RedisService redisService;

    @Override
    public List<String> findWhiteAddressList() {
        LambdaQueryWrapper<WhiteList> wrapper = new LambdaQueryWrapper();
        wrapper.eq(WhiteList::getValid, true);
        List<WhiteList> whiteLists = whiteListDao.selectList(wrapper);
        List<String> collect = whiteLists.stream().map(WhiteList::getAddress).collect(Collectors.toList());
        return collect;
    }

    @Override
    public void insertWhiteList(WhiteListDto whiteListDto) {
        WhiteList whiteList = new WhiteList();
        whiteList.setValid(true);
        whiteList.setCreateName(whiteListDto.getCreateName());
        whiteList.setAddress(whiteListDto.getAddress());
        whiteListDao.insert(whiteList);
    }

    @Override
    public void updateWhiteList(WhiteListDto whiteListDto) {
        WhiteList whiteList = whiteListDao.selectById(whiteListDto.getWhiteListId());
        whiteList.setAddress(whiteListDto.getAddress());
        whiteListDao.updateById(whiteList);
    }

    @Override
    public PageResult<WhiteListDto> findWhiteListPage(WhiteListQueryDto whiteListQueryDto) {
        Page<WhiteList> page = new Page<>(whiteListQueryDto.getPageNo(), whiteListQueryDto.getPageSize());
        IPage<WhiteListDto> iPage = whiteListDao.findWhiteListPage(whiteListQueryDto, page);
        return new PageResult<>(whiteListQueryDto.getPageNo(), whiteListQueryDto.getPageSize(), iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public void deleteWhiteListById(Integer whiteListId) {
        WhiteList whiteList = new WhiteList();
        whiteList.setValid(false);
        whiteList.setWhiteListId(whiteListId);
        whiteListDao.updateById(whiteList);
    }
}
